package com.ygqh.baby.handler;

import com.ygqh.baby.service.FileService;
import com.ygqh.baby.solr.YgSolrClient;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * 搜索词处理器
 *
 * @Author: sunshuo
 * @Date: 2019/3/14 18:11
 * @Version: 1.0
 */
@Component
public class SearchWordsHandler {

	private final SolrClient solrClient = YgSolrClient.INSTANCE.getSolrClient();
	private final Logger logger = LoggerFactory.getLogger(SearchWordsHandler.class);

	@Autowired
	private FileService fileService;

	/**
	 * 填充分词到远程分词库
	 *
	 * @param wordsList 分词
	 */
	public void fillSegmentRemoteMainDic(List<String> wordsList) {
		Assert.notEmpty(wordsList, "待填充分词为空");

		String key = "solr/dict/ext.dic";
		byte[] bytes = fileService.downloadFromOss(key);
		Assert.notNull(bytes, "远程分词库不存在");

		OutputStreamWriter osw = null;
		ByteArrayOutputStream os = null;
		try {
			os = new ByteArrayOutputStream();
			os.write(bytes, 0, bytes.length);
			osw = new OutputStreamWriter(os, "utf-8");
			for (String words : wordsList) {
				osw.write(words);
				osw.write("\r\n");
			}
			osw.flush();

			bytes = os.toByteArray();
			fileService.upload2Oss(key, bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 重载Solr分词库
	 *
	 * @return Boolean
	 */
	/*public Boolean reloadSolrMainDic() {
		NamedList<String> nameList = new NamedList<>(1);
		nameList.add(CommonParams.QT, "/ikanalyzer/reloadwords");
		QueryResponse response;
		try {
			response = new QueryRequest(SolrParams.toSolrParams(nameList)).process(solrClient);
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
			return false;
		}
		System.out.println("重载Solr分词库response=" + response);
		NamedList result = (NamedList) response.getResponse().get("result");
		if ("error".equals(result.get("type"))) {
			logger.error("重载Solr分词库失败，" + result.get("message").toString());
		}
		return result.getBooleanArg("reload");
	}*/

	/**
	 * 重置索引；
	 * 使用dataimport重新导入数据到solr
	 */
	public void refreshSolrIndex() {
		NamedList<String> nameList = new NamedList<>(1);
		nameList.add(CommonParams.QT, "/dataimport");
		// 是否决定在建立索引之前，删除以前的索引
		nameList.add("clean", Boolean.FALSE.toString());
		/*
		 * 指令：
		 * full-import 完全导入；
		 * delta-import 增量导入；
		 * status 命令执行的状态;
		 * reload-config 动态重载配置data-config.xml;
		 * abort 终止一个在运行的操作;
		 */
		nameList.add("command", "full-import");
		// 决定这个操作之后是否要commit
		nameList.add("commit", Boolean.TRUE.toString());
		QueryResponse response = null;
		try {
			response = new QueryRequest(SolrParams.toSolrParams(nameList), SolrRequest.METHOD.POST).process(solrClient);
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		}
		System.out.println("重置索引response=" + response);
	}
}
